<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
				</div>
				<div class="flex-start-center">
					<jk-select v-model="searchParams.workshopId" :clearable="false" placeholder="区域" :option-list="workshopList" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onDateChange"></jk-select>
					<jk-date-picker v-model="searchParams.belongDate" type="date" :clearable="false" :picker-options="pickerOptions" placeholder="日期" size="small" class="search-bar-item-size2 margin-5-0 item-gap" @change="onDateChange"></jk-date-picker>
					<el-select v-model="searchParams.scheduleShiftId" :disabled="!searchParams.belongDate" size="small" :clearable="false" placeholder="班次" class="search-bar-item-size3 margin-5-0 item-gap">
						<el-option
							v-for="item in scheduleShiftList"
							:key="item.id"
							:label="`${item.shiftName} (${item.beginTime} ~ ${item.endTime})`"
							:value="item.id"
						></el-option>
					</el-select>
					<jk-search-input v-model="searchParams.productNameOrCode" placeholder="品种编号或名称" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.machineNameOrCode" placeholder="机台编号或名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table ref="jkTable" :span-method="mergeColMethod" border :loading="tableLoading" :data="tableData" :height="tableHeight + 20">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<span v-if="item.keyName === 'machineName'" class="link-style" @click="onSeeBtn(scope.row)">{{ scope.row[item.keyName] }}</span>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<detail-dialog
			:data-item="detailDialogParams"
			:dialog-state="detailDialogState"
			@on-visible-change="onVisibleChange"
		></detail-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, formatDate, formatTime, tipsBar } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import {
        productionMachineIneffectiveYieldRecordsMachinePage, productionMachineTonYarnEnergyPage
    } from '../../../api/production/reports';
    import detailDialog from './detail-dialog';
    import XEUtils from 'xe-utils';
    import { workforcemanagementScheduleList } from '../../../api/schedule/scheduling';
    import { workforcemanagementScheduleShiftByTime } from '../../../api/schedule/empReplacePost';
    export default {
        name: 'ShiftProductEnergyConsumptionStatistics',
        components: {
            detailDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                apiItem: {
                    'page': productionMachineTonYarnEnergyPage
                },
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                detailDialogState: false,
                scheduleShiftList: [],
                workshopList: [],
                tableLoading: true,
                tableData: [],
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    workshopId: null,
                    scheduleShiftId: null,
                    machineNameOrCode: '',
                    productNameOrCode: '',
                    belongDate: ''
                },
                detailDialogParams: {}
            };
        },
        mounted() {
            this.getDependentData();
        },
        methods: {
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                if (row.belongDate && column.property === 'productName') {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow.belongDate === row.belongDate) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow.belongDate === row.belongDate) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onDateChange() {
                this.$set(this.searchParams, 'scheduleShiftId', null);
                this.scheduleShiftList = [];
                this.getDateScheduleShiftOptionRequest();
            },
            onSeeBtn(e) {
                this.detailDialogParams = {
                    workshopId: this.searchParams.workshopId,
                    belongDate: this.searchParams.belongDate,
                    scheduleShiftId: this.searchParams.scheduleShiftId,
                    machineId: e.machineId,
                    machineName: e.machineName,
                    productId: e.productId,
                    productName: e.productName
                };
                this.detailDialogState = true;
            },
            onVisibleChange(e) {
                this.detailDialogState = e;
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getDateScheduleShiftOptionRequest() {
                if (this.searchParams.workshopId && this.searchParams.belongDate) {
                    return workforcemanagementScheduleList({
                        belongDate: [this.searchParams.belongDate, this.searchParams.belongDate],
                        workshopId: this.searchParams.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res;
                            if (resData && resData.length) {
                                this.scheduleShiftList = resData[0].scheduleShiftList;
                                this.$set(this.searchParams, 'scheduleShiftId', this.scheduleShiftList && this.scheduleShiftList.length ? this.scheduleShiftList[0].id : null);
                            }
                        }
                    });
                }
            },
            getScheduleShiftForTimeRequest() {
                if (this.searchParams.workshopId && this.searchParams.belongDate) {
                    return workforcemanagementScheduleShiftByTime({
                        startTime: formatTime(Date.now()),
                        workshopId: this.searchParams.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res;
                            if (resData) {
                                this.$set(this.searchParams, 'scheduleShiftId', resData.id);
                            }
                        }
                    });
                }
            },
            async getDependentData() {
                this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
                this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode);
                this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;

                this.tableLoading = true;
                await this.getMenuColumnListRequest();
                await this.getDateScheduleShiftOptionRequest();
                await this.getScheduleShiftForTimeRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            /** 查询列表 */
            getListRequest() {
                this.tableData = [];
                if (this.searchParams.workshopId && this.searchParams.belongDate && this.searchParams.scheduleShiftId) {
                    this.tableLoading = true;
                    const params = JSON.parse(JSON.stringify(this.searchParams));
                    return this.apiItem['page'](params).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.tableData = res.data.res;
                            this.totalCount = res.data.count;
                        }
                    });
                } else {
                    tipsBar(this, 'custom', 'warning', '区域、机台、班次不能为空!');
                }
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            }
        }
    };
</script>
<style>
</style>
